package com.payment.ktb.Fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.main4.ProfitDetailResearchActivity;
import com.payment.ktb.adapter.AdapterProfitDetail;
import com.payment.ktb.adapter.OrderManageAdapter;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.OrderManageEntity;
import com.payment.ktb.model.ProfitDetailEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/12/5.
 */

public class FragmentProfitManageProfitDetail extends BaseFragment implements View.OnClickListener{


    View view;
    TextView tv_fragmentprofitmanageprofitdetail_timestart;
    TextView tv_fragmentprofitmanageprofitdetail_timeend;
    Button btn_fragmentprofitmanageprofitdetail_research;
    PullToRefreshListView prlv_fragmentprofitmanageprofitdetail;

    String ts = new SimpleDateFormat("yyyy-MM").format(new Date()) + "-01 00:00:00";
    String te = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 23:59:59";
    private int page = 0;
    private List<ProfitDetailEntity> listDatas = new ArrayList<>();
    private AdapterProfitDetail adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        view = inflater.inflate(R.layout.fragmentprofitmanageprofitdetail,container,false);
        initData();


        return view;


    }

    private void initData() {
        tv_fragmentprofitmanageprofitdetail_timestart = (TextView) view.findViewById(R.id.tv_fragmentprofitmanageprofitdetail_timestart);
        tv_fragmentprofitmanageprofitdetail_timestart.setOnClickListener(this);
        tv_fragmentprofitmanageprofitdetail_timeend = (TextView) view.findViewById(R.id.tv_fragmentprofitmanageprofitdetail_timeend);
        tv_fragmentprofitmanageprofitdetail_timeend.setOnClickListener(this);
        btn_fragmentprofitmanageprofitdetail_research = (Button) view.findViewById(R.id.btn_fragmentprofitmanageprofitdetail_research);
        btn_fragmentprofitmanageprofitdetail_research.setOnClickListener(this);
        prlv_fragmentprofitmanageprofitdetail = (PullToRefreshListView) view.findViewById(R.id.prlv_fragmentprofitmanageprofitdetail);

        // 设置下拉刷新加载文本
        prlv_fragmentprofitmanageprofitdetail.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
        prlv_fragmentprofitmanageprofitdetail.getLoadingLayoutProxy(true, false).setReleaseLabel("放开刷新...");
        prlv_fragmentprofitmanageprofitdetail.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
        // 设置上拉加载文本
        prlv_fragmentprofitmanageprofitdetail.getLoadingLayoutProxy(false, true).setPullLabel("上拉刷新...");
        prlv_fragmentprofitmanageprofitdetail.getLoadingLayoutProxy(false, true).setReleaseLabel("放开刷新...");
        prlv_fragmentprofitmanageprofitdetail.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
        tv_fragmentprofitmanageprofitdetail_timestart.setText(new SimpleDateFormat("yyyy-MM").format(new Date()) + "-01");
        tv_fragmentprofitmanageprofitdetail_timeend.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        prlv_fragmentprofitmanageprofitdetail.setMode(PullToRefreshBase.Mode.BOTH);
        prlv_fragmentprofitmanageprofitdetail.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新
                pullDownToRefresh();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pullUptoLoad();


            }
        });
        pullDownToRefresh();

    }


    /**
     *
     */
    private void showStartDateDialog() {

        ToastUtils.showToast("请选择开始时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                ts = time + " 00:00:00";
                tv_fragmentprofitmanageprofitdetail_timestart.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }



    /**
     *
     */
    private void showEndDateDialog() {

        ToastUtils.showToast("请选择结束时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                te = time + " 23:59:59";
                tv_fragmentprofitmanageprofitdetail_timeend.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            //开始时间
            case R.id.tv_fragmentprofitmanageprofitdetail_timestart:
                showStartDateDialog();
                break;

            //结束时间
            case R.id.tv_fragmentprofitmanageprofitdetail_timeend:
                showEndDateDialog();
                break;

            //搜索
            case R.id.btn_fragmentprofitmanageprofitdetail_research:

                Intent intent = new Intent(mContext, ProfitDetailResearchActivity.class);
                intent.putExtra("ts",ts);
                intent.putExtra("te",te);
                startActivity(intent);

                break;

        }
    }






    private void pullDownToRefresh() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = 0;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgProfitRecord, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_fragmentprofitmanageprofitdetail.onRefreshComplete();
                    listDatas.clear();

                    //data
                    listDatas = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<ProfitDetailEntity>>() {}.getType());
                    if (listDatas == null || listDatas.isEmpty()) {
                        listDatas = new ArrayList<ProfitDetailEntity>();
                        ToastUtils.showToast("没有数据！");
                    }
                    //adapter
                    adapter = new AdapterProfitDetail(mContext, listDatas);
                    //bind
                    prlv_fragmentprofitmanageprofitdetail.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_fragmentprofitmanageprofitdetail.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }






    private void pullUptoLoad() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = page + 1;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgProfitRecord, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {

                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_fragmentprofitmanageprofitdetail.onRefreshComplete();
                    //data
                    List<ProfitDetailEntity> profitDeatils = null;
                    profitDeatils = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<ProfitDetailEntity>>() {}.getType());

                    if (profitDeatils != null && !profitDeatils.isEmpty()) {
                        //adapter
                        listDatas.addAll(profitDeatils);
                        adapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.showToast("没有更多数据啦！");
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_fragmentprofitmanageprofitdetail.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }







}
